package token

import (
	"coolcar/v1/shared/ids"
	"crypto/rsa"
	"github.com/dgrijalva/jwt-go"
	"time"
)

// JWTTokenGenerator generates a JWT token.
type JWTTokenGenerator struct {
	privateKey *rsa.PrivateKey
	issuer     string
	nowFunc    func() time.Time
}

// NewJWTTokenGenerator creates a new JWTTokenGenerator.
func NewJWTTokenGenerator(issuer string, privateKey *rsa.PrivateKey) *JWTTokenGenerator {
	return &JWTTokenGenerator{
		privateKey: privateKey,
		issuer:     issuer,
		nowFunc:    time.Now,
	}
}

// Generate generates a token.
func (j *JWTTokenGenerator) Generate(aid ids.AccountID, expired time.Duration) (string, error) {
	now := j.nowFunc().Unix()
	tkn := jwt.NewWithClaims(jwt.SigningMethodRS512, &jwt.StandardClaims{
		Subject:   aid.String(),
		IssuedAt:  now,
		ExpiresAt: now + int64(expired.Seconds()),
		Issuer:    j.issuer,
	})
	return tkn.SignedString(j.privateKey)
}
